<template>
  <Dialog
    v-model="dialogVisible"
    align-center
    width="1720px"
    :fullscreen="false"
    :closable="false"
    style="transform: translateX(100px); height: 800px;"
  >
    <template #title>
      <span>详细信息</span>
      <div style="margin-left: auto">
        <el-button
          type="primary"
          :loading="loading"
          @click="() => handleSave()"
        >
          保 存
        </el-button>
        <el-button
          @click="() => handleCancel()"
        >
          返 回
        </el-button>
      </div>
    </template>
    <div class="wrapper">
      <div>
        <ContentWrap class="info-area" title="基本信息">
          <template v-if="Boolean(info)">
            <el-form
              class="info-form"
              v-loading="loading"
              :model="info"
              :rules="rules"
              label-width="6em"
            >
              <el-form-item label="姓名" prop="username">
                <el-input v-model="info.username" placeholder="请填写姓名" disabled />
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="info.mobile" placeholder="请填写手机号码" type="tel" disabled />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="info.sex">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                    :key="dict.value"
                    :value="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model="info.age" placeholder="请填写年龄" />
              </el-form-item>
              <el-form-item label="贷款额度" prop="quota">
                <el-input-number
                  v-model="info.quota"
                  placeholder="请输入贷款额度"
                  align="left"
                  :min="0"
                  :precision="2"
                  style="width: 100%;"
                  :controls="false"
                >
                  <template #suffix>元</template>
                </el-input-number>
              </el-form-item>
              <el-form-item label="跟进人" prop="followUpName">
                <el-input v-model="info.followUpName" placeholder="请填写跟进人" disabled />
              </el-form-item>
            </el-form>
          </template>
          <template v-else>无</template>
        </ContentWrap>
        <ContentWrap class="type-in-area" title="快捷录入">
          <el-form
            v-loading="loading"
            :model="info"
            :rules="rules"
            label-width="6em"
          >
            <el-form-item label="房产" prop="realestate">
              <el-radio-group v-model="info.realestate" style="flex-wrap: nowrap;">
                <el-radio-button
                  v-for="dict in getIntDictOptions(DICT_TYPE.REALESTATE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="公积金" prop="housingProvidentFund">
              <el-radio-group v-model="info.housingProvidentFund" style="flex-wrap: nowrap;">
                <el-radio-button
                  v-for="dict in getIntDictOptions(DICT_TYPE.HOUSINGPROVIDENTFUND)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="社保" prop="socialinsurance">
              <el-radio-group v-model="info.socialinsurance" style="flex-wrap: nowrap;">
                <el-radio-button
                  v-for="dict in getIntDictOptions(DICT_TYPE.SOCIALINSURANCE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="跟进状态"
              prop="followUpStatus"
              style="grid-row-start: 2; grid-column: 1 / 2;"
            >
              <el-select
                v-model="info.followUpStatus"
                placeholder="请选择跟进状态"
                class="!w-120px"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUPSTATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <el-button
                v-if="'成功放款' == getDictLabel(DICT_TYPE.FOLLOWUPSTATUS, info.followUpStatus)"
                type="primary"
                link
                @click="() => showLoanDialog()"
              >
                录入放款信息
              </el-button>
            </el-form-item>
            <el-form-item
              label="跟进次数"
              prop="followUpFrequency"
              style="grid-row-start: 5; grid-column-end: 2;">
              <el-input-number v-model="info.followUpFrequency" :min="0" disabled />
            </el-form-item>
            <el-form-item
              label="客户星级"
              prop="starRating"
              style="grid-row-start: 3; grid-column-end: 2;"
            >
              <el-select
                v-model="info.starRating"
                placeholder="请选择客户星级"
                clearable
                style="width: 150px;"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMERSTARRATING)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="跟进备注"
              prop="followRemark"
              style="width: 540px; align-self: end; grid-row: 2 / span 2; grid-column: 2 / span 2;"
            >
              <el-input
                v-model="info.followRemark"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请填写跟进备注"
              />
              <!-- 快捷话语选择区域 -->
              <div class="quick-remarks">
                <el-tag
                  v-for="(remark, index) in quickRemarks"
                  :key="index"
                  type="info"
                  size="small"
                  class="remark-tag"
                  @click="insteadQuickRemark(remark)"
                >
                  {{ remark }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item
              label="条件备注"
              prop="remark"
              style="width: 540px; align-self: end; grid-row: 4 / span 2; grid-column: 2 / span 2"
            >
              <el-input
                v-model="info.remark"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请填写条件备注"
              />
            </el-form-item>
            <div
              style="
                display: grid;
                gap: 14px;
                margin-left: 14px;
                grid-row: 5 / span 1;
                grid-column: 4 / span 1;
              "
            >
              <el-button
                class="pseudo-form-item"
                type="primary"
                :disabled="!prevInfo"
                link
                @click="() => handleSetIndex(-1)"
              >
                <div class="pseudo-input">
                  <span class="label">上一客户：</span>
                  {{ prevInfo ? prevInfo.username : '无' }}
                </div>
              </el-button>
              <el-button
                class="pseudo-form-item"
                type="primary"
                :disabled="!nextInfo"
                link
                style="margin: 0px;"
                @click="() => handleSetIndex(1)"
              >
                <div class="pseudo-input">
                  <span class="label">下一客户：</span>
                  {{ nextInfo ? nextInfo.username : '无' }}
                </div>
              </el-button>
            </div>
          </el-form>
        </ContentWrap>
      </div>
      <div>
        <ContentWrap class="history-area" title="跟进记录">
          <header class="list-header">
            <div>跟进人</div>
            <div>跟进备注</div>
            <div>跟进时间</div>
          </header>
          <template v-if="!history.list.length">暂无记录</template>
          <ol class="history-list">
            <li v-for="item in history.list" :key="item.id">
              <span class="name">
                {{ item.followUserName }}
              </span>
              <span class="remark">
                {{ item.remark }}
              </span>
              <span>
                {{ dateFormatter(void 0, void 0, item.createTime) }}
              </span>
            </li>
          </ol>
        </ContentWrap>
        <ContentWrap class="loan-area" title="放款记录">
          <header class="list-header">
            <div>跟进人</div>
            <div>放款金额（元）</div>
            <div>放款时间</div>
          </header>
          <template v-if="!loan.list.length">暂无记录</template>
          <ol class="loan-list">
            <li v-for="item in loan.list" :key="item.id">
              <span class="name">
                {{ item.followUserName }}
              </span>
              <span class="loanAmount" style="text-align: center">
                {{ item.loanAmount }}
              </span>
              <span>
                {{ dateFormatter(void 0, void 0, item.loanTime) }}
              </span>
            </li>
          </ol>
        </ContentWrap>
      </div>
    </div>
  </Dialog>
  <loanForm
    ref="loanFormRef"
    @success="
      () => {
        getLoanPage()
      }
    "
  />
</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel, getIntDictOptions } from '@/utils/dict'
import { customerApi } from '@/api/system/customer'
import { dateFormatter } from '@/utils/formatTime'
import { clamp, cloneDeep, isEqual, omit } from 'lodash-es'
import { ElMessage, ElMessageBox } from 'element-plus'
import loanForm from './loanForm.vue'
import { loanApi } from '@/api/system/loan'
import { MyCustomerApi } from '@/api/system/mycustomer'

const props = defineProps({
  save: {
    required: true,
    type: Function,
  },
  getInfoListMethod: {
    required: true,
    type: Function,
  },
  getInfoMethod: {
    required: true,
    type: Function,
  },
  infoList: {
    required: true,
    type: Array,
  },
  getHistoryMethod: {
    required: true,
    type: Function,
  },
  getLoanPageMethod: {
    required: true,
    type: Function,
  },
});

const emit = defineEmits(['save']);
const dialogVisible = ref(false);
watch(dialogVisible, value => !value && props.getInfoListMethod());

const loading = ref(false)

const infoIndex = ref(0);
const prevInfo = computed(() => {
  return props.infoList[infoIndex.value - 1];
});

const nextInfo = computed(() => {
  return props.infoList[infoIndex.value + 1];
});

const currentInfo = computed(() => {
  return props.infoList[infoIndex.value];
});

const info = ref({});
// 保存后不能直接更新表格了
// 因为 getInfoList() 后表格数据顺序会变
// currentInfo 和 info 不能直接对比
/** 保存一份 info 修改前的样子 */
const infoInitial = ref();

const loan = ref({
  list: [],
  total: 0
});

watch(
  () => props.infoList,
  () => {
    infoIndex.value = clamp(infoIndex.value, 0, props.infoList.length)
  }
);

watch(
  currentInfo,
  () => dialogVisible.value && init()
);

const rules = {
  username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  quota: [
    { required: true, message: '贷款额度不能为空', trigger: 'change' },
    {
      validator(rule, value, callback) {
        return 0 < value ? callback() : callback(new Error('贷款额度不能为0'));
      },
    }
  ],
  mobile: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
  followUpFrequency: [{ required: true, message: '跟进次数不能为空', trigger: 'change' }],
  followTime: [{ required: true, message: '跟进时间不能为空', trigger: 'change' }],
  followUpName: [{ required: true, message: '跟进人不能为空', trigger: 'change' }],
  followRemark: [{ required: true, message: '跟进备注不能为空', trigger: 'change' }],
  followUpStatus: [{ required: true, message: '跟进状态不能为空', trigger: 'change' }],
  remark: [{ required: true, message: '客户条件备注不能为空', trigger: 'blur' }],
  source: [{ required: true, message: '来源不能为空', trigger: 'change' }],
  starRating: [{ required: true, message: '客户星级不能为空', trigger: 'change' }],
  realestate: [{ required: true, message: '房产不能为空', trigger: 'change' }],
  housingProvidentFund: [{ required: true, message: '公积金不能为空', trigger: 'change' }],
  socialinsurance: [{ required: true, message: '社保不能为空', trigger: 'change' }]
}

const history = ref({
  list: [],
  total: 0
});

function getHistory() {
  loading.value = true
  return props.getHistoryMethod(info.value)
    .then((data) => {
      history.value = data
    })
    .finally(() => {
      loading.value = false
    })
}

function getLoanPage() {
  loading.value = true
  return props.getLoanPageMethod(info.value)
    .then((data) => {
      loan.value = data
    })
    .finally(() => {
      loading.value = false
    })
}

function handleSetIndex(change) {
  if (isEqual(info.value, infoInitial.value)) {
    infoIndex.value += change
    return;
  }

  ElMessageBox({
    type: 'warning',
    title: '存在更改',
    message: '当前信息未保存，确定切换用户吗？',
    showClose: false,
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback(action) {
      'confirm' === action && (infoIndex.value += change);
    },
  })
}

function handleSave() {
  loading.value = true;

  return props
    .save(info, infoInitial)
    .then(() => {
      ElMessage.success('已保存');
      getHistory();
      getLoanPage();
      infoInitial.value = cloneDeep(info.value);
      emit('save');
    })
    .finally(() => {
      loading.value = false
    })
}

function handleCancel() {
  if (isEqual(info.value, infoInitial.value)) {
    dialogVisible.value = false;
    return;
  }

  ElMessageBox({
    type: 'warning',
    title: '存在更改',
    message: '当前信息未保存，确定返回吗？',
    showClose: false,
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback(action) {
      if ('confirm' === action) {
        dialogVisible.value = false;
      };
    },
  })
}

function init() {
  loading.value = true;
  props
  .getInfoMethod(currentInfo.value.id)
  .then(data => {
    info.value = cloneDeep(data);
    infoInitial.value = cloneDeep(data);

    if (!info.value) {
      ElMessage.info('当前页已无数据')
      dialogVisible.value = false;
      return
    }

    info.value.starRating = info.value.starRating && Number(info.value.starRating);
    // queryMarked();
    getHistory();
    getLoanPage();
  })
  .finally(() => {
    loading.value = false;
  });
}

function open(rowIndex) {
  infoIndex.value = rowIndex
  dialogVisible.value = true
  // 显示弹框前已触发 watch，但弹框显示状态为 false，被阻止调接口
  // 所以在刚打开时要调一下接口
  init();
}

const loanFormRef = ref()
function showLoanDialog() {
  loanFormRef.value.open('create', void 0, {
    myCustomerId: info.value.id,
    myCustomerName: info.value.username
  })
}
// 定义快捷话语数组
const quickRemarks = [
  '电话未接通',
  '暂时不需要',
  '过段时间需要',
  '在忙晚点联系',
]

/** 添加快捷话语到输入框 */
function insteadQuickRemark(remark: string) {
  info.value.followRemark = remark;
}
defineExpose({ open })
</script>

<style scoped>
.wrapper {
  display: grid;
  grid-template-columns: minmax(0,1fr) 500px;
}

.info-area {
  grid-area: info;
}

.type-in-area {
  grid-area: type-in;
}

.type-in-area :deep(.el-card__body) {
  width: 100%;
  height: 420px;
  overflow: auto;
}

.type-in-area .el-form {
  display: grid;
  height: 100%;
  align-items: center;
  align-content: space-between;
  grid-template-columns: repeat(3,max-content) minmax(0,1fr);
}

.type-in-area .el-form .el-form-item {
  margin: 0;
}

:deep(.pseudo-form-item),
:deep(.pseudo-form-item) > span {
  width: 100%;
}

:deep(.pseudo-form-item) .label {
  color: #606266;
}

.pseudo-input {
  flex: 1;
  padding-left: 6px;
  border: 1px solid #dcdfe6;
  line-height: 32px;
  text-align: left;
  border-radius: 4px;
}

.history-area {
  grid-area: history;
}

.history-area :deep(.el-card__body) {
  height: 448px;
}

.loan-area {
  grid-area: loan;
}

.loan-area :deep(.el-card__body) {
  height: 100px;
}

.info-area,
.history-area,
.loan-area {
  display: grid;
  grid-template-rows: auto minmax(0, 1fr);
}

:where(.history-area, .loan-area) :deep(.el-card__body) {
  height: 100%;
}

:where(.history-area, .loan-area) :deep(.el-card__body) > ol {
  overflow-y: auto;
  height: 100%;
}

.loan-area :deep(.el-card__body) > ol {
  overflow: hidden;
}

.history-area :deep(.el-card__body) > ol {
  height: calc(100% - 26px);
}

.loan-area :deep(.el-card__body) {
  display: grid;
  grid-template-rows: auto minmax(0, 1fr);
}

:where(.history-area, .loan-area) .list-header {
  display: grid;
  grid-template-columns: 80px minmax(0, 1fr) 155px;
  text-align: center;
  height: 40px;
  margin-bottom: 10px;
  color: #fff;
  background: #9fafb8 linear-gradient(180deg, rgba(255, 255, 255, 0.5), transparent 30%);
}

:where(.history-area, .loan-area) .list-header > div {
  line-height: 40px;
}
:where(.history-area, .loan-area) .list-header > div + div {
  border-left: 1px solid #f5f5f5;
}

:where(.history-list, .loan-list) > li {
  list-style: none;
  display: grid;
  align-items: center;
  gap: 10px;
  grid-template-columns: minmax(0, 80px) minmax(0, 1fr) 140px;
  margin-bottom: 10px;
}

:where(.history-list, .loan-list) > li .name {
  padding-left: 8px;
  align-self: stretch;
  line-height: 30px;
  color: #409eff;
  /* background: #f5f5f5; */
}

.info-form {
  display: grid;
  column-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}

.el-radio-group {
  width: 100%;
}

:deep(.el-radio-button__inner) {
  width: 6.5em;
  padding: 8px;
}

.quick-remarks {
  margin-bottom: 10px;
}

.remark-tag {
  cursor: pointer;
  margin-right: 8px;
  margin-bottom: 8px;
  background-color: #f0f9eb; /* 浅绿色背景 */
  border-color: #e1f3d8; /* 边框颜色 */
}

.remark-tag:hover {
  background-color: #f0f9eb; /* 悬停时保持背景色 */
  opacity: 0.8;
}
</style>
